//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from 'react';
import { observer } from 'mobx-react';
import { useDrawStores } from '../store';
import { Button, Card, message, Popover, Space } from 'antd';
import s from "./EditDraw.module.less";
import { get_session } from '@/api/user';
import { request } from '@/utils/request';
import { watch, unwatch, WATCH_TARGET_ENTRY } from '@/api/project_watch';
import { createTLStore, type Editor, exportToBlob, Tldraw } from 'tldraw';
import { COMMENT_TARGET_ENTRY } from '@/api/project_comment';
import CommentEntry from '@/components/CommentEntry';
import { MoreOutlined } from '@ant-design/icons';
import { save as dialog_save } from '@tauri-apps/api/dialog';
import { writeBinaryFile } from '@tauri-apps/api/fs';

const ReadDraw = () => {
    const store = useDrawStores();

    const [contentStore] = useState(createTLStore());
    const [editor, setEditor] = useState<Editor | null>(null);

    const watchDraw = async () => {
        const sessionId = await get_session();
        await request(watch({
            session_id: sessionId,
            project_id: store.projectId,
            target_type: WATCH_TARGET_ENTRY,
            target_id: store.drawId,
        }));
    };

    const unwatchDraw = async () => {
        const sessionId = await get_session();
        await request(unwatch({
            session_id: sessionId,
            project_id: store.projectId,
            target_type: WATCH_TARGET_ENTRY,
            target_id: store.drawId,
        }));
    };

    const exportDraw = async (exportType: "jpeg" | "png" | "svg" | "webp") => {
        if (editor == null) {
            return;
        }
        const filePath = await dialog_save({
            filters: [{
                name: "图片",
                extensions: [exportType],
            }]
        });
        if (filePath == null) {
            return;
        }
        const shapeIds = editor.getCurrentPageShapeIds();
        const data = await exportToBlob({
            editor,
            format: exportType,
            ids: Array.from(shapeIds),
        });
        const buffer = await data.arrayBuffer();
        await writeBinaryFile(filePath, buffer);
        message.info("导出成功");
    };

    useEffect(() => {
        if (store.draw != undefined && store.draw.content != "") {
            const data = JSON.parse(store.draw.content);
            contentStore.loadStoreSnapshot(data);
        }
    }, [store.draw?.content]);

    return (
        <Card title={
            <Space>
                <span className={store.entry?.my_watch == true ? s.isCollect : s.noCollect}
                    onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        if (store.entry?.my_watch == true) {
                            unwatchDraw();
                        } else {
                            watchDraw();
                        }
                    }} />
                <span style={{ fontSize: "16px", fontWeight: 700 }}>{store.entry?.entry_title ?? ""}</span>
            </Space>
        } extra={
            <Space style={{ marginRight: "10px" }}>
                <CommentEntry projectId={store.projectId} targetType={COMMENT_TARGET_ENTRY}
                    targetId={store.drawId} myUserId={store.myUserId} myAdmin={store.project?.user_project_perm.can_admin ?? false}
                    enableAdd={!(store.project?.closed ?? false)} />
                <Button
                    type="primary"
                    style={{ marginLeft: "10px" }}
                    disabled={store.project?.closed || !(store.entry?.can_update ?? false)}
                    onClick={(e) => {
                        e.stopPropagation();
                        e.preventDefault();
                        store.inEdit = true;
                    }}
                >
                    编辑
                </Button>
                {editor != null && (
                    <Popover trigger="click" placement='bottomRight' content={
                        <Space direction='vertical'>
                            <Button type="link" onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                exportDraw("jpeg");
                            }}>导出jpeg图片</Button>
                            <Button type="link" onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                exportDraw("png");
                            }}>导出png图片</Button>
                            <Button type="link" onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                exportDraw("webp");
                            }}>导出webp图片</Button>
                            <Button type="link" onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                exportDraw("svg");
                            }}>导出svg图片</Button>
                        </Space>
                    }>
                        <MoreOutlined />
                    </Popover>
                )}
            </Space>
        }
            bordered={false}
            bodyStyle={{ paddingBottom: "0px", width: "calc(100vw - 10px)" }}>
            <div className={s.draw_wrap}>
                <Tldraw store={contentStore}
                    components={{
                        ContextMenu: null,
                        MainMenu: null,
                        SharePanel: null,
                        CursorChatBubble: null,
                    }}
                    onMount={(newEditor) => {
                        if (newEditor != editor) {
                            setEditor(newEditor);
                        }
                        newEditor.updateInstanceState({ isReadonly: true });
                        newEditor.user.updateUserPreferences({
                            locale: "zh-cn",
                        });
                        setTimeout(() => {
                            newEditor.updateInstanceState({ isReadonly: true });
                            newEditor.user.updateUserPreferences({
                                locale: "zh-cn",
                            });
                        }, 200);
                    }} />
            </div>
        </Card>
    );
};

export default observer(ReadDraw);
